package cn.doitedu.realtime_rule_web.switchdb;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DataSourceConfig {

    @Autowired
    private Environment env;

    /**
     *  65.38.37.235为主数据库
     *  主数据库配置
     */
    @Bean("mysql")
    @ConfigurationProperties(prefix = "spring.datasource.mysql")
    public DataSource masterDataSource(){
        DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
        dataSourceBuilder.driverClassName(env.getProperty("spring.datasource.mysql.driver-class-name"));
        dataSourceBuilder.url(env.getProperty("spring.datasource.mysql.url"));
        dataSourceBuilder.username(env.getProperty("spring.datasource.mysql.username"));
        dataSourceBuilder.password(env.getProperty("spring.datasource.mysql.password"));
        return dataSourceBuilder.build();
    }

    /**
     *  65.38.37.141 为从数据库
     *  从数据库配置
     */
    @Bean("slave")
    @ConfigurationProperties(prefix = "spring.datasource.doris")
    public DataSource slaveDataSource(){

        DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
        dataSourceBuilder.driverClassName(env.getProperty("spring.datasource.doris.driver-class-name"));
        dataSourceBuilder.url(env.getProperty("spring.datasource.doris.url"));
        dataSourceBuilder.username(env.getProperty("spring.datasource.doris.username"));
        dataSourceBuilder.password(env.getProperty("spring.datasource.doris.password"));

        return dataSourceBuilder.build();
    }


    /**
     *  动态数据源配置
     */
    @Primary
    @Bean(name = "dynamicDataSource")
    public DataSource dynamicDataSource(){
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        //默认数据源
        dynamicDataSource.setDefaultTargetDataSource(masterDataSource());

        //配置多数据源
        Map<Object, Object> dsMap = new HashMap<Object, Object>(5);
        dsMap.put("mysql", masterDataSource());
        dsMap.put("doris", slaveDataSource());
        dynamicDataSource.setTargetDataSources(dsMap);
        return dynamicDataSource;
    }

    /**
     * 配置@Transactional注解事物
     *  @return
     */
    @Bean
    public PlatformTransactionManager transactionManager(){
        return new DataSourceTransactionManager(dynamicDataSource());
    }
}